package com.ly.wxstore.service;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ly.wxstore.comm.Delete;
import com.ly.wxstore.comm.MyPage;
import com.ly.wxstore.entity.UserAddress;
import com.ly.wxstore.repository.UserAddressDao;
import com.ly.wxstore.web.AddressController;

/**
 * 
 * 
 * @author Peter
 */
// Spring Service Bean的标识.
@Component
public class UserAddressService {
	private static Logger logger = LoggerFactory.getLogger(UserAddressService.class);

	@Autowired
	private UserAddressDao userAddressDao;

	public UserAddress getById(Long id) {
		return userAddressDao.getById(id);
	}

	public List<UserAddress> getAll() {
		return userAddressDao.getAll();
	}

	/**
	 * 分页查询
	 * 
	 * @param overtime
	 * @param pageStart
	 * @param pageSize
	 * @return
	 */
	public MyPage<UserAddress> searchPage(UserAddress userAddress, int currentPage, int pageSize) {
		MyPage<UserAddress> myPage = new MyPage<UserAddress>();

		Long count = userAddressDao.searchCount(userAddress);

		int pageStart = (currentPage - 1) < 0 ? 0 : (currentPage - 1) * pageSize;
		List<UserAddress> list = userAddressDao.searchPage(userAddress, pageStart, pageSize);

		myPage.setCount(count);
		myPage.setContent(list);

		return myPage;
	}

	public void createOrUpdate(UserAddress userAddress) {
		if(userAddress.getId()!=null && userAddress.getId().longValue()>0){
			userAddress.setUpdateDate(new Date());
			userAddressDao.update(userAddress);
		}else{
			userAddress.setDeleted(Delete.Enabled.longValue());
			userAddress.setCreateDate(new Date());
			userAddress.setUpdateDate(new Date());
			userAddressDao.save(userAddress);
		}
	}

	public void update(UserAddress userAddress) {
		userAddressDao.update(userAddress);
	}

	/**
	 * 软删除
	 */
	public void delete(Long id) {
		userAddressDao.delete(id);
	}

	public List<UserAddress> getAllBySid(String sid) {
		return userAddressDao.getAllBySid(sid);
	}

	/**
	 * 获取默认的收货地址，如果有多个默认的收货地址，使用第一条；如果没有默认收货地址，则使用最新添加的收货地址；否则返回null
	 * 
	 * @param sid
	 * @return
	 */
	public UserAddress getDefaultBySid(String sid) {
		UserAddress defAddress = null;
		List<UserAddress> list = userAddressDao.getDefaultBySid(sid);
		if (list == null || list.size() == 0) {
			list = userAddressDao.getAllBySid(sid);
			if (list != null && list.size() > 0) {
				defAddress = list.get(0);
			}
		} else {
			defAddress = list.get(0);
		}

		return defAddress;
	}

}
